<template>
	<view class="container">
		<view class="dataBox">
			<view class="column" v-for="(item,index) in level" :key="index" :style="{background:index == 0 ? '#f2f2f2' : '#fff'}">
				<view class="column-item" :class="result[index]&&result[index].value == child.id ? 'active' : ''" v-for="(child,ins) in trees[index]" :key="ins" @click="selectNode(child,index)">
					{{child.name}}
				</view>
			</view>
		</view>
		<view class="bottom" @click="onConfirm">确定</view>
	</view>
</template>

<script>
	export default {
		props: {
			treeData: {
				type: Array,
				default: () => {
					return []
				}
			}
		},
		data() {
			return {
				level:0,
				list:[],
				trees:{},
				result:{}
			}
		},
		mounted() {
		},
		watch:{
			treeData:{
				handler:function(newVal,oldVal){
					this.list = newVal
					this.level = this.getLevel(newVal)
					this.trees[0] = this.list
					for(var i = 0;i < this.level;i++){
						this.$set(this.result, i, null)
					}
				},
				deep:true
			}
		},
		methods: {
			getLevel(arr){
				let maxLevel = 0;
				(function callBack(arr, level) {
					++level;
					maxLevel = Math.max(level, maxLevel);
					for (let i = 0; i < arr.length; i++) {
						let item = arr[i];
						if (item.children && item.children.length > 0) {
							callBack(item.children, level);
						} else {
							delete item.children;
						}
					}
				})(arr, 0);
				return maxLevel;
			},
			selectNode(data, index){
				this.$set(this.result,(index),{
					value:data.id,
					name:data.name
				})
				if(index < this.level - 1){
					this.$set(this.trees, (index+1), data.children || [])
					
					for(var key in this.trees){
						if(key > index + 1){
							this.$set(this.trees, key, [])
						}
						if(key > index){
							this.$set(this.result, key, null)
						}
					}
				}
				
			},
			onConfirm(){
				this.$emit('onConfirm', this.result)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: flex-start;
		flex-direction: column;
		justify-content: space-between;
	}

	.dataBox {
		width: 100%;
		flex-grow: 1;
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		height:100%;
		.column{
			flex: 1;
			height:100%;
		}
		.column-item{
			text-align: center;
			font-size: 28rpx;
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.active{
			background: $uni-color-opatity;
			color: $uni-color-theme;
		}
	}

	.bottom {
		flex-shrink: 0;
		width: 100%;
		background: $uni-color-theme;
		color: #fff;
		font-size: 28rpx;
		text-align: center;
		padding: 20rpx;
	}
</style>